package dk.itu.samd.group2.tagapastry.indexing;

import java.util.ArrayList;
import java.util.Vector;

import dk.itu.samd.group2.tagapastry.ChildrenMapper;
import dk.itu.samd.group2.tagapastry.IndexEntry;
import dk.itu.samd.group2.tagapastry.IndexRelative;
import dk.itu.samd.group2.tagapastry.Tag;
import dk.itu.samd.group2.tagapastry.TagapastryImpl;

public class SimpleDistributionStrategy implements DistributionStrategy {

	public SimpleDistributionStrategy(TagapastryImpl tagaImpl) {
		this.tagaImpl = tagaImpl;
	}

	@Override
	public void distribute(Tag tag, Vector<IndexEntry> entries, Vector<IndexRelative> children) {
		ChildrenMapper mapper = new ChildrenMapper();
		//System.out.println("Calling IndexExpansion...");
		
		// Create buckets
		ArrayList<Vector<IndexEntry>> buckets = new ArrayList<Vector<IndexEntry>>(mapper.getChildrenNum());
		for (char i : mapper) {
			buckets.add(new Vector<IndexEntry>());
		}
		
		//System.out.println("Entries to bucket: ");
		// put entries in buckets
		for (IndexEntry entry : entries) {
			char childChar = entry.getHash().charAt(tag.getExtension().length());
			int index = mapper.get(childChar);
			buckets.get(index).add(entry);
		}
				
		for (char i : mapper) {
			Vector<IndexEntry> bucket = buckets.get(mapper.get(i));
			if (!bucket.isEmpty()) {
				IndexRelative child = children.get(mapper.get(i));
				child.expand(tagaImpl, bucket);
			}
		}
	}
	
	private final TagapastryImpl tagaImpl;

}
